var express = require('express');
var router = express.Router();
var User = require('../models/users');
var md5 = require('md5');
var multipart = require('connect-multiparty');  //用来接收formdate的中间件
var multipartMiddleware = multipart();
var fs = require('fs');
var path = require('path');

//保存到数据库
function save (postData,res){
     // 查询是否被注册
     User.findOne({ username: postData.username }, function (err, data) {
        if (data) {
            // res.send(data);
            res.send({
                state: 0,
                msg: "用户名已被注册"
            })
        } else {
            
            // 保存到数据库
            User.create(postData, function (err, data) {
                console.log(postData)
                if (err) throw err;
                console.log('注册成功');
                res.send({
                    state: 1,
                    msg: "注册成功"
                })
            })
        }
    });
}

/* POST users listing. */
router.post('/', multipartMiddleware, function (req, res, next) {
    // 获取用户提交的信息
    var postData = {
        username: req.body.username,
        password: md5(req.body.password),
        role: req.body.role,
        head: req.body.head
    };
    
    // console.log(req)
    if (!req.files.head) {
        // 没有传头像图片文件
        save(postData,res)
        return;
    } else {
        var filePath = req.files.head.path;
        var fileName = req.files.head.originalFilename;
        console.log(req.files.head)
        fs.readFile(filePath, function (err, data) {
            var timestamp = Date.now();
            var newPath = path.join(__dirname, "../../", "/public/images/" + fileName)
            console.log('path: '+ req.files.head.path.slice(7))
            postData.filePath = req.files.head.path.slice(14)
            fs.writeFile(newPath, data, function (err) {
               if (err) console.log(err)
               save(postData,res)
            })
        })
    }
    // 输出文件信息
    console.log('====================================================');
    console.log('fieldname: ' + req.files.head.fieldName);
    console.log('originalname: ' + req.files.head.originalFilename);
    console.log('mimetype: ' + req.files.head.type);
    console.log('size: ' + (req.files.head.size / 1024).toFixed(2) + 'KB');
    console.log('filesname: ' + req.files.head.name);
    console.log('path: ' + req.files.head.path);

});

/* GET users listing. */
router.get('/', function (req, res, next) {
    var userList = User.find({}, function (err, data) {
        if (err) throw err;
        data.forEach(function(item,index){
            item.filePath = 'http://192.168.6.211:3000/images/'+item.filePath
        })
        res.send(data)
    });
})
module.exports = router;
